// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate
const db_users = db.collection('user');

//操作excel用的类库
const xlsx = require('node-xlsx');

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event)
  switch (event.action) {
    case 'getUserAll':
      return getUserAll(event)
    case 'getUser':
      return getUser(event)
    case 'exportUser':
      return exportUser(event)
    default:
      return
  }
}

//导出user数据
async function exportUser(event) {
  try {
    let userList = event.userList;
    console.log(userList)
  
    const name = '用户.xlsx';
    let alldata = []
    let row = ['序号', '姓名', '工号', '部门', '状态']
    alldata.push(row)

    // let data = orderList.data
    let data = userList
    for (const key in data) {
      let arr = []
      console.log(key)
      arr.push(parseInt(key) + 1)
      arr.push(data[key].name)
      arr.push(data[key].number)
      arr.push(data[key].department)
      arr.push(data[key].status)
      alldata.push(arr)
    }

    //3，把数据保存到excel里
    let buffer = await xlsx.build([{
      name: '用户',
      data: alldata
    }])

    //4，把excel文件保存到云存储里
    return await cloud.uploadFile({
      cloudPath: name,
      fileContent: buffer
    })

  } catch (error) {
    console.error(error)
    return error
  }

}

function getUser(e) {
  let page = e.page
  let pageSize = e.pageSize
  let data = {}
  if (e.department != undefined || e.department == ''){
    data.department = e.department
  }
  return db_users.where(data).orderBy('department','desc').skip(page*pageSize).limit(pageSize).get({
    success: res => {
      console.log(res)
    }
  })
}